
package org.sourcecode.common.rpc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class ThriftIfaceAccessor {

	protected final Log log = LogFactory.getLog(getClass());

	private TSocketPoolFactory pool;

	public <T> T mcall(String serviceName,ThriftIface<T> iface) throws Exception{
		TSocket socket = null;
		socket = pool.getConnection();
		T t = null;
		try {
			TTransport transport = new TFramedTransport(socket);
			TProtocol protocol = new TBinaryProtocol(transport);
			TMultiplexedProtocol muProtocol = new TMultiplexedProtocol(protocol, serviceName);
			t = iface.call(muProtocol);
		} finally {
			pool.returnConnection(socket);
		}
		return t;
	}

	public void setPool(TSocketPoolFactory pool){
		this.pool = pool;
	}

	public TSocketPoolFactory getPool(){
		return pool;
	}

}
